package org.jeecg.modules.wmhb.job;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wmhb.entity.WmContract;
import org.jeecg.modules.wmhb.entity.WmProject;
import org.jeecg.modules.wmhb.entity.WmTask;
import org.jeecg.modules.wmhb.service.IWmContractProductService;
import org.jeecg.modules.wmhb.service.IWmContractService;
import org.jeecg.modules.wmhb.service.IWmProjectService;
import org.jeecg.modules.wmhb.service.IWmTaskService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProjectProgressJob implements Job {
    @Autowired
    private IWmProjectService wmProjectService;
    @Autowired
    private IWmContractService wmContractService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" =============ProjectProgressJob============ !  时间:" + DateUtils.getTimestamp()));
        List<WmProject> wmProjectList = wmProjectService.confirmedProjectList();
        for(WmProject wmProject: wmProjectList) {
            BigDecimal progress = new BigDecimal(0);

            //项目的所有合同
            List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(wmProject.getId());
            if(!wmContractList.isEmpty()) {
                BigDecimal fenziTotal = new BigDecimal(0);
                BigDecimal fenmuTotal = new BigDecimal(0);
                for(WmContract wmContract: wmContractList) {
                    fenziTotal = fenziTotal.add((new BigDecimal(wmContract.getProgress())).multiply(new BigDecimal(wmContract.getWeight())));
                    fenmuTotal = fenmuTotal.add(new BigDecimal(wmContract.getWeight()));
                }
                progress = fenmuTotal.compareTo(BigDecimal.ZERO) == 0 ? (new BigDecimal(0)) : (fenziTotal.divide(fenmuTotal, RoundingMode.HALF_UP));
            }

            wmProject.setProgress(progress.toString());
            wmProjectService.updateById(wmProject);
        }
    }
}
